//
//  ImportLinkerNextViewController.m
//  GC_OC
//
//  Created by tuibian  on 2022/5/28.
//

#import "ImportLinkerNextViewController.h"
#import "HelpAlertView.h"
#import "LinkerModel.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "ChooseCategoryAlertView.h"

@interface ImportLinkerNextViewController ()<UITextViewDelegate>
@property(nonatomic, strong) UIView *navigationBarView;
@property(nonatomic, strong) UILabel *categoryLabel;
@property(nonatomic, strong) UIButton *deleteButton;
@property(nonatomic, strong) UIButton *confirmButton;
@property(nonatomic, strong) UILabel *totalLabel;
@property(nonatomic, strong) UILabel *failLabel;
@property(nonatomic, strong) UILabel *successLabel;
@property(nonatomic, strong) UITextView *textView;
@property(nonatomic, strong) UILabel *placeholder;
@property(nonatomic, strong) ChooseCategoryAlertView *chooseCategoryAlertView;


@end

@implementation ImportLinkerNextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUIView];
     
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTextChange) name:UITextViewTextDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardWillShow:) name:UIKeyboardWillShowNotification object:nil];
     
        //键盘将要结束时候的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardDidHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [IQKeyboardManager sharedManager].enable = YES;
}

-(void)boardWillShow:(NSNotification *)notification{
    
    //获取键盘高度，
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    [self.textView.superview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.deleteButton.mas_top).offset(-kbHeight + 145 - 34);
    }];
    
    
//    [UIView animateWithDuration:[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
//
//      //改变输入框的y值和view的高度
////        self.bottomView.y = kHeight - 50 - kbHeight;
////        self.mainTableView.height = kHeight - 50 - kbHeight;
//
//    }];
    
}
 
//键盘将要结束
-(void)boardDidHide:(NSNotification *)notification{
    
     //恢复输入框的y值和view的高度
//    self.bottomView.y = kHeight - 50 ;
//    self.mainTableView.height = kHeight - 50;
//    self.messageView.placeholder = @"请输入留言信息";
    
    [self.textView.superview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.deleteButton.mas_top).offset(-42);
    }];
}

- (void)didTextChange {
    NSLog(@"===%@",self.textView.text);
    NSString *text = [self.textView.text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    if ([text stringByReplacingOccurrencesOfString:@" " withString:@""].length != 0) {
        self.placeholder.hidden = YES;
        self.deleteButton.backgroundColor = XHUIColorFromRGB(0x0091FF);

    } else {
        self.totalLabel.hidden = YES;
        self.failLabel.hidden = YES;
        self.successLabel.hidden = YES;

        self.placeholder.hidden = NO;
        self.deleteButton.backgroundColor = XHUIColorFromRGBA(0x0091FF, 0.16);
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.totalLabel.hidden = NO;
    self.failLabel.hidden = NO;
    self.successLabel.hidden = NO;

    NSString *text = self.textView.text;
    
    NSArray *array = [text componentsSeparatedByString:@"http"];
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
    for (NSString *str in array) {
        if (str.length != 0) {
            [tempArray addObject:[NSString stringWithFormat:@"http%@", str]];
        }
    }
    
    NSInteger errorCount = 0;
    for (NSString *str in tempArray){
        if (![str containsString:@"http://"] && ![str containsString:@"https://"] && ![str containsString:@".mp3"]) {
            errorCount += 1;
        }
    }
    
    self.totalLabel.text = [NSString stringWithFormat:@"导入%ld行", tempArray.count];
    self.failLabel.text = [NSString stringWithFormat:@"失败%ld行", errorCount];
    self.successLabel.text = [NSString stringWithFormat:@"成功%ld行", tempArray.count - errorCount];

}

- (void)setupUIView {
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.navigationBarView];
    
    UILabel *naviTitle = [UILabel new];
    naviTitle.text = @"外链导入";
//    naviTitle.textAlignment = NSTextAlignmentCenter;
    naviTitle.userInteractionEnabled = YES;
    naviTitle.textColor = [UIColor blackColor];
    naviTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.navigationBarView addSubview:naviTitle];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [naviTitle addGestureRecognizer:tap];
    
    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"icon_返回_32_left"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    
    UIButton *exitButton = [UIButton new];
    [exitButton setTitle:@"帮助" forState:UIControlStateNormal];
    [exitButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [exitButton addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:exitButton];
    
    UIView *view = [UIView new];
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = XHUIColorFromRGB(0x999999).CGColor;
    view.backgroundColor = XHUIColorFromRGB(0xf2f2f2);
    [self.view addSubview:view];
    
    self.categoryLabel = [UILabel new];
    self.categoryLabel.text = [NSString stringWithFormat:@"%@-%@",self.fModel.name, self.sModel.name];
    self.categoryLabel.userInteractionEnabled = YES;
    self.categoryLabel.textColor = [UIColor blackColor];
    self.categoryLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [view addSubview:self.categoryLabel];
    
    //箭头
    UIImageView *button = [UIImageView new];
    button.userInteractionEnabled = YES;
    button.image = [UIImage imageNamed:@"箭头 三角形"];
//    button.contentMode = UIViewContentModeScaleAspectFit;
    [view addSubview:button];
    
    UITapGestureRecognizer *btTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseCategory)];
    [view addGestureRecognizer:btTap];
    
    UIView *aidLineView = [UIView new];
    aidLineView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:aidLineView];
    
    self.deleteButton = [UIButton new];
    [self.deleteButton setTitle:@"清空" forState:UIControlStateNormal];
    self.deleteButton.backgroundColor = XHUIColorFromRGBA(0x0091FF, 0.16);
    self.deleteButton.layer.masksToBounds = YES;
    self.deleteButton.layer.cornerRadius = 22.5;
    [self.deleteButton setImage:[UIImage imageNamed:@"删除2"] forState:UIControlStateNormal];
    [self.deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.deleteButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.deleteButton addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.deleteButton];
    
    self.confirmButton = [UIButton new];
    self.confirmButton.backgroundColor = XHUIColorFromRGB(0x0091FF);
    self.confirmButton.layer.masksToBounds = YES;
    self.confirmButton.layer.cornerRadius = 22.5;
    [self.confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.confirmButton addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmButton];
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];

    self.textView = [UITextView new];
    self.textView.delegate = self;
    self.textView.textColor = [UIColor blackColor];
    self.textView.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [bgView addSubview:self.textView];
    
    self.placeholder = [UILabel new];
    self.placeholder.text = @"一行一个音频，可批量导入\n\nhttp:xxx.com/123.mp3#标题\nhttp:xxx.com/123.mp3#标题";
    self.placeholder.textColor = XHUIColorFromRGBA(0x000000, 0.24);
    self.placeholder.numberOfLines = 0;
    self.placeholder.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [bgView addSubview:self.placeholder];
    
    self.totalLabel = [UILabel new];
    self.totalLabel.hidden = YES;
    self.totalLabel.text = @"导入0行";
    self.totalLabel.textColor = XHUIColorFromRGB(0x6D7278);
    self.totalLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:self.totalLabel];
    
    self.failLabel = [UILabel new];
    self.failLabel.hidden = YES;
    self.failLabel.text = @"失败0行";
    self.failLabel.textAlignment = NSTextAlignmentCenter;
    self.failLabel.textColor = XHUIColorFromRGBA(0xFA6400, 0.24);
    
    self.failLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:self.failLabel];
    
    self.successLabel = [UILabel new];
    self.successLabel.hidden = YES;
    self.successLabel.textAlignment = NSTextAlignmentRight;
    self.successLabel.text = @"成功0行";
    self.successLabel.textColor = XHUIColorFromRGB(0x0091FF);
    self.successLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:self.successLabel];
    
    [self.view addSubview:self.chooseCategoryAlertView];
    
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(NAVI_BAR_HIGHT);
    }];
    [naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.left.equalTo(backButton.mas_right).offset(0);
        make.top.mas_equalTo(StatusBarHeight);
        make.height.mas_equalTo(40);
    }];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.navigationBarView).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(32);
        make.width.mas_equalTo(40);

        make.right.equalTo(self.navigationBarView).offset(-12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.categoryLabel);
        make.height.width.mas_equalTo(36);
        make.right.equalTo(view).offset(-24);
    }];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.navigationBarView.mas_bottom).mas_equalTo(10);
    }];
    
    [self.categoryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(30);
        make.height.mas_equalTo(44);
        make.right.equalTo(view).offset(0);
        make.centerY.equalTo(view).offset(0).offset(0);
        
    }];
    
    [aidLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(1);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_equalTo(-54);
    }];

    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(105);
        make.centerY.equalTo(aidLineView);
        make.right.equalTo(aidLineView.mas_left).mas_equalTo(-30);
    }];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(105);
        make.centerY.equalTo(aidLineView);
        make.left.equalTo(aidLineView.mas_right).mas_equalTo(30);
    }];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(9);
        make.right.equalTo(self.view).offset(-7);
        make.top.equalTo(view.mas_bottom).offset(9);
        make.bottom.equalTo(self.deleteButton.mas_top).offset(-42);
    }];
    
    [self.totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(18);
        make.width.greaterThanOrEqualTo(@150);
    }];
    
    [self.failLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(18);
        make.width.greaterThanOrEqualTo(@150);
    }];
    [self.successLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(18);
        make.width.greaterThanOrEqualTo(@150);
    }];
    
//    [self.view layoutIfNeeded];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView).offset(16);
        make.top.equalTo(bgView).offset(24);
        make.right.equalTo(bgView).offset(-16);
        make.bottom.equalTo(bgView).offset(-24);
//        make.height.mas_equalTo(bgView.frame.size.height - 48);
    }];
//    self.textView.backgroundColor = [UIColor redColor];
    
    [self.placeholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textView).offset(4);
        make.top.equalTo(self.textView).offset(6);
//        make.height.mas_equalTo(18);
        make.right.equalTo(self.textView).offset(0);
    }];
}

- (void)clearAction {
    if ([self.textView.text stringByReplacingOccurrencesOfString:@" " withString:@""].length != 0) {
        self.textView.text = nil;
        self.deleteButton.backgroundColor = XHUIColorFromRGBA(0x0091FF, 0.16);
    }
    
}
- (void)confirmAction {
    [self.view endEditing:YES];
    
    NSString *text = self.textView.text;
    
    NSArray *array = [text componentsSeparatedByString:@"http"];
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
    for (NSString *str in array) {
        if (str.length != 0) {
            [tempArray addObject:[NSString stringWithFormat:@"http%@", str]];
        }
    }
    
//    NSInteger errorCount = 0;
//    for (NSString *str in tempArray){
//        if (![str containsString:@"#"]) {
//            errorCount += 1;
//        }
//    }
//
//    self.totalLabel.text = [NSString stringWithFormat:@"导入%ld行", tempArray.count];
//    self.failLabel.text = [NSString stringWithFormat:@"失败%ld行", errorCount];
//    self.successLabel.text = [NSString stringWithFormat:@"成功%ld行", tempArray.count - errorCount];
    
    NSMutableArray *tArray = [NSMutableArray arrayWithCapacity:0];
    for (NSString *str in tempArray) {
        if ([str containsString:@"#"]) {
            NSArray *tempDataSource = [str componentsSeparatedByString:@"#"];
            LinkerModel *obj = [LinkerModel new];
            obj.type = @3;
            obj.name = [tempDataSource lastObject];
            obj.url = [tempDataSource firstObject];
            [tArray addObject:obj];
        } else {
            //取文件名
            NSArray *tempDataSource = [str componentsSeparatedByString:@"/"];
            LinkerModel *obj = [LinkerModel new];
            obj.type = @3;
            obj.name = [tempDataSource lastObject];
            obj.url = str;
            [tArray addObject:obj];
        }
    }
    if (!self.sModel.list) {
        self.sModel.list = [NSMutableArray arrayWithCapacity:0];
    }
    [self.sModel.list addObjectsFromArray:tArray];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BNYTRefreshUI" object:nil userInfo:nil];
    
    [self.navigationController popToViewController:self.navigationController.viewControllers[2] animated:YES];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)editAction {
    HelpAlertView *alerView = [HelpAlertView new];
    [alerView showIn:self.view];
}

- (void)chooseCategory {
    //弹窗选择二级分类
    self.chooseCategoryAlertView.dataSource = self.dataSource;
    [self.chooseCategoryAlertView showIn:self.view];
    __weak typeof(self) ws = self;
    self.chooseCategoryAlertView.confirmBlock = ^{
        //确定选中
        LinkerModel *fModel;
        LinkerModel *sModel;
        for (LinkerModel *obj in ws.dataSource) {
            for (LinkerModel *model in obj.list) {
                if ([model.isSelect isEqual:@1]) {
                    fModel = obj;
                    sModel = model;
                }
            }
        }
        if (fModel && sModel) {
            ws.fModel = fModel;
            ws.sModel = sModel;
            ws.categoryLabel.text = [NSString stringWithFormat:@"%@-%@",fModel.name, sModel.name];
        }
    };
}
- (ChooseCategoryAlertView *)chooseCategoryAlertView {
    if (!_chooseCategoryAlertView) {
        _chooseCategoryAlertView = [ChooseCategoryAlertView new];
    }
    return _chooseCategoryAlertView;
}
@end
